$(document).ready(function (e) {
    var liWidth = $(".rightbox_content").width();
    var searchtotal = 0;
    /*$('#searchIds').selectpicker({
     liveSearch: true,
     selectAllText:"全选",
     noneSelectedText:"请选择",
     deselectAllText:"取消选中项",
     actionsBox:true//在下拉选项添加选中所有和取消选中的按钮
     /!*maxOptions: 4,
     maxOptionsText:"<b><strong>最多选择4项</strong></b>"*!/
     });*/
    var currentHosName = "";
    var hosTotalTableList = [];
    var hosMap = {};
    var zanWu = getBaseName() + "/resources/images/statics/zanwu.png";

    $(".search").on("click", function (e) {
        reschartsearch();
    });
    $(".export").on("click", function (e) {
        $("#exportForm").submit();
    });
    var content = $("#chooseTimeTemplate").tmpl().html();
    $(".uploadAppImg").popover({
        trigger: 'manual',
        placement: 'bottom', //top, bottom, left or right
        title: "选择时间<i class='glyphicon glyphicon-remove pull-right remove'></i>",
        html: 'true',
        content: content
    }).on("click", function (e) {
        $(this).popover("show");
        var date = new Date();
        var nowTime = date.Format("yyyy-MM-dd HH:mm:ss");
        var startTime;
        $(".dateBtn").on("click", function () {
            var me = this;
            var flag = false;
            $(".dateBtn").each(function (index, el) {
                if ($(this).hasClass("timeActive")) {
                    if (el == me) {
                        flag = true;
                    }
                    $(this).removeClass("timeActive");
                }
            });
            if (!flag) {
                $(this).addClass("timeActive");
                switch ($(this).text()) {
                    case "1周":
                        startTime = reduceDays(date, 7);
//					 $("#startTime1").val(startTime)；
                        break;
                    case "1月":
                        startTime = reduceMonths(date, 1);
//                    $("#startTime1").val(startTime).attr("disabled", "disabled");
                        break;
                    case "3月":
                        startTime = reduceMonths(date, 3);
//                    $("#startTime1").val(startTime).attr("disabled", "disabled");
                        break;
                    case "1年":
                        startTime = reduceYears(date, 1);
//                    $("#startTime1").val(startTime).attr("disabled", "disabled");
                        break;
                    default:
                        alert("没有该选项！");
                }
                $("#startTime1").val(startTime);
                $("#endTime1").val(nowTime);
                $("#startTime1_val").text(startTime);
                $("#endTime1_val").text(nowTime);
                $("#startTime1").datepicker("update");
                $("#endTime1").datepicker("update");
            } else {
                $(this).removeClass("timeActive");
            }
        });
        /*$('.input-daterange').datepicker({
         format: "yyyy-mm-dd",
         todayBtn: "linked",
         language: "zh-CN",
         autoclose: true,
         todayHighlight: true
         });*/
        $('#startTime1').datepicker({
            format: "yyyy-mm-dd",
            todayBtn: "linked",
            language: "zh-CN",
            autoclose: true,
            todayHighlight: true
        }).on("changeDate", function (e) {
            $('#' + $(this).attr("id") + "_val").text($(this).val());
        });
        $('#endTime1').datepicker({
            format: "yyyy-mm-dd",
            todayBtn: "linked",
            language: "zh-CN",
            autoclose: true,
            todayHighlight: true
        }).on("changeDate", function (e) {
            $('#' + $(this).attr("id") + "_val").text($(this).val());
        });
        /*
         $('.input-daterange').datepicker({
         format: "yyyy-mm-dd",
         todayBtn: "linked",
         language: "zh-CN",
         autoclose: true,
         todayHighlight: true
         }).on("changeDate",function(e){
         var id = $(this).find("input").attr("id");
         $('#'+id+"_val").text($(this).find("input").val());
         });
         */
    }).on("mouseleave", function () {
        /*$(this).popover("hide");*/
    });
    $(".uploadAppImg").popover("show");
    $(".popover").hide();
    $(".rightbox_content").delegate(".remove", "click", function (e) {
        /*$(".uploadAppImg").popover("hide");*/
        $(".popover").hide();
    });
    /*$('#searchIds').multiselect({
     /!*enableFiltering: true,*!/
     enableCaseInsensitiveFiltering: true,
     includeSelectAllOption: true,
     filterPlaceholder: '搜索',
     selectAllText: "全选",
     nonSelectedText: '请选择',
     selectAllText: '全选/取消全选',
     allSelectedText: '已选中所有选项',
     nSelectedText: '项被选中'
     });*/

    function showEmpty(dom) {
        dom.append("<h3 class='center'>抱歉，暂无数据！</h3>");
    }

    function showTable(tableList, flag, name) {
        tableList.sort(function (a, b) {
            return a.ratio - b.ratio < 0;
        });
        $(".hosRatioTable tbody").empty();
        if (flag) {
            $(".headtable #th_title b").text("系统内访问的次数统计表");
            $(".headtable #th_name").text("系统名称");
        } else if (!flag) {
            $(".headtable #th_title b").text(name + "内资源被访问的次数统计表");
            $(".headtable #th_name").text("资源名称");
        }
        $("#hosTableTemplate").tmpl(tableList).appendTo($(".hosRatioTable tbody"));
    }

    var setEvent = function () {
        $(".gaugeChart").on("click", function (e) {
            var id = ($(this).attr("id"));
            if (id.indexOf("total") > 0) {
                show("resourcepieH");
                $("#resourcepbarH").empty();
                showTable(hosTotalTableList, true, null);
                $("#expHosId").val("");
            } else {
                var idAll = $(this).attr("id");
                var hosId = idAll.substring(idAll.indexOf("_") + 1);
                changeH($(this).attr("hosname"), hosId);
            }
        });
    }
    var showSearch = function (result) {
        show("resourcepieH");
        console.log(result);
        var hospitals = result.hospitals;
        var appHosCountMap = result.appHosCountMap;
        var totalCount = 0;
        var hosCount = hospitals.length;
        for (var v in appHosCountMap) {
            totalCount += appHosCountMap[v];
        }
        var tableList = [];
        var piedata = [];
        var param = {
            gaugeid: "gauge_total",
            gaugeclass: "gauge_total",
            hosname: "总计",
        }
        $(".henarea .gaugearea").empty();
        $(".henarea .gaugearea").append('<li class="gaugeGroup" id="gaugeLi0"><div class="one"></div></li>');
        var liCount = 0;
        var guageLiCount = Math.ceil(hospitals.length / 4);
        $(".henarea .gaugearea").width(liWidth * guageLiCount);
        $(".henarea  .gaugearea #gaugeLi" + liCount).width(liWidth);
        $("#hosTemplate").tmpl(param).appendTo($("#gaugeLi0 .one"));
        showGaugeH2('gauge_total', totalCount, totalCount, "#fa5b57");
        $.each(hospitals, function (i, v) {
            var trdata = {};
            var count = appHosCountMap[v.hosid];
            hosMap[v.hosname] = v.hosid;
            count = count != undefined ? count : 0;
            trdata.name = v.hosname;
            trdata.value = count;
            trdata.ratio = totalCount != 0 ? ((count / totalCount) * 100).toFixed(2) : 0;
            var onedata = [v.hosname, Number(count)];
            piedata.push(onedata);
            trdata.ratio = totalCount != 0 ? ((count / totalCount) * 100).toFixed(2) : 0;
            tableList.push(trdata);
            var param = {

                gaugeid: "gauge_" + v.hosid,
                gaugeclass: "gauge_total",
                hosname: v.hosname
            }

            if (i % 4 == 3) {
                liCount = Math.ceil(i / 4);
                $(".gaugearea").append('<li class="gaugeGroup" id=gaugeLi' + liCount + '><div class="one"></div></li>');
            }
            $("#hosTemplate").tmpl(param).appendTo($("#gaugeLi" + liCount + " .one"));
            $(".henarea  .gaugearea #gaugeLi" + liCount).width(liWidth);
            showGaugeH2("gauge_" + v.hosid, count, totalCount);
        });
        if (hosCount < 3) {
            var noInfo = 3 - hosCount;
            for (var i = 0; i < noInfo; i++) {
                $("#gaugeLi" + liCount + " .row").append('<div class="col-sm-3"><div class="well center"><div class="noSystem">暂无系统</div><div class="gaugeChart"><img class="noSysImg" src="' + zanWu + '"></div></div></div>');
            }
        }
        setEvent();
        //save total tableList
        hosTotalTableList = tableList;
        showTable(tableList, true, null);
        showPieH(piedata);
        $('.henarea').slides({
            effect: 'slide',
            container: 'gaugearea',
            generateNextPrev: true,
            pagination: false,
            generatePagination: false
        });
    }
    var totalsummary = function () {
        $("#statisSearchForm").ajaxSubmit({
            type: "GET",
            url: totalsummaryUrl,
            beforeSend: function (e) {
                $(".appinfo").append(LoadingImg);
            },
            data: {},
            success: function (result) {
                if (!isJson(result)) {
                    return false;
                }
                console.log(result);
                $(".appinfo").empty();
                $("#appinfoTemplate").tmpl(result).appendTo($(".appinfo"));
                showSearch(result);
            }
        });
    }

    var showProgress = function (data) {
        data.searchtotal = searchtotal;
        console.log(data);
        $("#appPieTemplate").tmpl(data).appendTo(".apppertlist");
        $.each($(".apppertlist .progress-bar"), function (i, v) {
            console.log(v);
            $(v).width($(v).attr("aria-valuenow") + "%");
        });
    };
    var reschartsearch = function () {

        $("#statisSearchForm").ajaxSubmit({
            dataType: "json",
            /*data: {appid: id},*/
            type: "post",
            success: function (result, status, xhr) {
                if (!isJson(result)) {
                    return false;
                }
                showSearch(result);
            }
        });

    }

    totalsummary();

    var showGaugeH = function (gaugeid, name, count, totalCount) {
        var chart = new Highcharts.Chart({
            chart: {
                type: 'solidgauge',
                renderTo: gaugeid
            },
            exporting: {
                enabled: false
            },
            credits: {
                enabled: false
            },
            pane: {
                center: ['50%', '80%'],
                size: '160%',
                startAngle: -90,
                endAngle: 90,
                background: {
                    backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || '#EEE',
                    innerRadius: '60%',
                    outerRadius: '100%',
                    shape: 'arc'
                }
            },
            tooltip: {
                enabled: false
            },
            // the value axis
            yAxis: {
                min: 0,
                max: totalCount,
                stops: [
                    [0.1, '#55BF3B'], // green
                    [0.5, '#DDDF0D'], // yellow
                    [0.9, '#DF5353'] // red
                ],
                lineWidth: 0,
                minorTickInterval: null,
                tickPixelInterval: 400,
                tickWidth: 0,
                title: {
                    y: -70
                },
                labels: {
                    y: 16
                }
            },
            plotOptions: {
                solidgauge: {
                    dataLabels: {
                        y: 5,
                        borderWidth: 0,
                        useHTML: true
                    }
                }
            },
            title: {
                text: name,
                y: 35
            },
            series: [{
                name: 'count',
                data: [count],
                dataLabels: {
                    format: '<div style="text-align:center"><span style="font-size:12px;color:silver">总共请求：</span><span style="font-size:20px;color:' +
                    ((Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black') + '">{y}</span><br/>' +
                    '</div>',
                    x: -50,
                    y: 45
                }
            }]
        });

    }
    var showPieH = function (data) {

        if (data.length == 0) {
            data.datetip = "该院内系统暂无调用数据！";
            $("#dateTipTemplate").tmpl(data).replaceAll($("#commonModal .modal-content"));
            $("#commonModal").modal("show");
            return false;
        }
        var chart = $('.resourcepie').highcharts({
            chart: {
                type: 'pie',
                options3d: {
                    enabled: true,
                    alpha: 60
                },
                events: {}
            },
            lang: {
                downloadJPEG: "下载JPEG图片",
                downloadPDF: "下载PDF文件",
                downloadPNG: "下载PNG文件",
                downloadSVG: "下载SVG文件",
                loading: "加载中",
                noData: "没有数据",
                printChart: "打印图表11"
            },
            exporting: {
                enabled: true,
                url: getBaseName() + "/json/highchars/export"
            },
            credits: {
                enabled: false
            },
            title: {
                text: '系统访问次数统计图',
                y: 20
            },
            tooltip: {
                pointFormat: '占比: <b>{point.percentage:.2f}%</b>'
            },
            plotOptions: {
                pie: {
                    innerSize: 175,
                    depth: 30,
                    dataLabels: {
                        enabled: true,
                        format: '<b>{point.name}</b>: {point.percentage:.2f} %',
                        style: {
                            fontFamily: 'Microsoft YaHei'
                        }
                    }
                },
                series: {
                    cursor: 'pointer',
                    point: {
                        events: {
                            click: function () {
                                currentHosName = this.name;
                                var hosId = hosMap[currentHosName];
                                changeH(this.name, hosId);
                            }
                        }
                    }
                }
            },
            xAxis: {
                name: []
            },
            series: [{
                name: 'Delivered amount',
                data: data
            }]
        });
    }

    function changeH(name, hosId) {
        $.ajax({
            type: "GET",
            url: getBaseName() + "/json/newstatic/hosrescount",
            data: {
                hosname: name,
                appid: appid,
                starttime: $("[name=startDate]").val(),
                endtime: $("[name=endDate]").val()
            },
            success: function (result) {
                console.log(result);
                if (result.hasResource) {
                    hidden("resourcepieH");
                    $("#expHosId").val(hosId);
                } else {
                    if (!result.hasResource) {
                        result.datetip = name + "系统暂无调用数据！";
                        $("#dateTipTemplate").tmpl(result).replaceAll($("#commonModal .modal-content"));
                        $("#commonModal").modal("show");
                        return false;
                    }
                }
                var data = {
                    resNames: [],
                    counts: []
                };
                var tableList = [];
                var totalCount = 0;
                for (var i in result.hoscount) {
                    totalCount += result.hoscount[i];
                }

                $.each(result.resources, function (i, value) {
                    data.resNames.push(value.resourcename);
                    var count = result.hoscount[value.resno];
                    data.counts.push(count);
                    var tr = {
                        name: value.resourcename,
                        value: count,
                        ratio: totalCount != 0 ? (count * 100 / totalCount).toFixed(2) : 0
                    }
                    tableList.push(tr);
                });
                showBarH(result);
                showTable(tableList, false, name);
            }
        });
    }

    //===============//
    var showBarH = function (data) {
        var resnames = [];
        var counts = [];
        $.each(data.resources, function (i, value) {
            resnames.push(value.resourcename);
            counts.push(data.hoscount[value.resno]);
        });
        var gaugeOptions = new Highcharts.Chart({
            chart: {
                type: 'bar',
                renderTo: resourcepbarH
            },
            lang: {
                downloadJPEG: "下载JPEG图片",
                downloadPDF: "下载PDF文件",
                downloadPNG: "下载PNG文件",
                downloadSVG: "下载SVG文件",
                loading: "加载中",
                noData: "没有数据",
                printChart: "打印图表"
            },
            exporting: {
                enabled: true,
                url: getBaseName() + "/json/highchars/export"
            },
            legend: {
                enabled: false
            },
            title: {
                text: '系统访问统计图'
            },
            xAxis: {
                categories: resnames,
                labels: {
                    style: {
                        fontFamily: 'Microsoft YaHei'
                    }
                }
            },
            yAxis: {
                min: 0,
                title: {
                    text: '请求次数',
                    align: 'high'
                },
                labels: {
                    style: {
                        fontFamily: 'Microsoft YaHei'
                    }
                }
            },
            credits: {
                enabled: false
            },
            series: [{
                name: '请求次数',
                data: counts
            }],
            plotOptions: {
                series: {
                    dataLabels: {
                        enabled: true
                    }
                }
            }
        });
    }

    function show(div) {
        document.getElementById(div).style.display = "";
    }

    function hidden(div) {
        document.getElementById(div).style.display = "none";
    }

    //===//
    var showGaugeH2 = function (gaugeid, count, totalCount, color) {
        if (color == undefined) {
            color = '#629ed5';
        }
        var chart = new Highcharts.Chart({
            chart: {
                type: 'pie',
                renderTo: gaugeid,
                marginTop: 15
            },
            title: {
                text: '总共请求:' + count,
                align: 'center',
                verticalAlign: 'bottom',
                y: -10
            },
            exporting: {
                enabled: false
            },
            credits: {
                enabled: false
            },
            tooltip: {
                enabled: false
            },
            plotOptions: {
                pie: {
                    colors: [color, '#cccccc'],
                    dataLabels: {
                        enabled: true,
                        distance: -20,
                        style: {
                            fontWeight: 'bold',
                            color: 'white',
                            textShadow: '0px 1px 2px black'
                        },
                        format: '{point.percentage:.2f} %'
                    },
                    startAngle: -90,
                    endAngle: 90,
                    center: ['50%', '75%'],
                    size: '160%'
                }
            },
            series: [{
                name: '',
                innerSize: '50%',
                data: [
                    {
                        name: '',
                        y: count
                    },
                    {
                        name: '',
                        y: totalCount - count,
                        dataLabels: {
                            enabled: false
                        }
                    }
                ]
            }]
        });
    }

});
